/* Copyright 2008 Bas van den Berg
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Messages.h"
#include "Error.h"
#include "myassert.h"
#include "Utils.h"

using namespace Chronos;
using namespace std;


void Messages::addMessage(const std::string& message, unsigned int weight) {
    unsigned int highest = messages.empty() ? 0 : messages.back().weight;
    messages.push_back(Message(weight + highest, message));
}


const std::string& Messages::getMessage() const {
    ASSERT_FALSE(messages.empty());
    unsigned int highest = messages.back().weight;
    return messages[getIndex(Utils::roll(1, highest))].message;
}


unsigned int Messages::getIndex(unsigned int num) const {
    const unsigned int count = messages.size();
    unsigned int i = 0;
    while (i < count) {
        if (num <= messages[i].weight) return i;
        i++;
    }
    ASSERT_FAIL();
    return 0;   // to satisfy compiler
}

